package web.eshop.tree;

import domain.shop.Category;
import org.apache.wicket.model.LoadableDetachableModel;
import org.springframework.beans.factory.annotation.Autowired;
import service.facade.customer.ShopCustomerService;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import java.util.List;

/**
 * Tree model container contains all categories.
 */
public class CategoryTreeModelContainer extends LoadableDetachableModel {

    @Autowired
    private ShopCustomerService customerService;

    public CategoryTreeModelContainer() {
    }

    @Override
    protected Object load() {
        return createTreeModel();
    }

    /**
     * Create tree model.
     *
     * @return
     */
    public TreeModel createTreeModel() {
        return convertToTreeModel(customerService.findCategoryRoots());
    }

    /**
     * Converts List<Category> to tree model.
     * That "Object" should have reasonable toString() method.
     *
     * @param list
     * @return
     */
    private TreeModel convertToTreeModel(List<Category> list) {
        DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("ROOT");
        add(rootNode, list);
        TreeModel model = new DefaultTreeModel(rootNode);
        return model;
    }

    /**
     * Create whole tree structures.
     *
     * @param parent
     * @param sub
     */
    private void add(DefaultMutableTreeNode parent, List<Category> sub) {
        for (Category mp : sub) {
            List childs = customerService.findCategoryChildsByParentId(mp.getId());
            if (childs.size() != 0) {
                DefaultMutableTreeNode subParent = new DefaultMutableTreeNode(mp);
                parent.add(subParent);
                add(subParent, childs);
            } else {
                DefaultMutableTreeNode child = new DefaultMutableTreeNode(mp);
                parent.add(child);
            }
        }
    }
}



